package vn.game;

import java.util.ArrayList;
import java.util.Random;
import android.app.Activity;
import android.content.Context;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.BitmapDrawable;
import android.os.Bundle;
import android.os.Handler;
import android.text.Editable;
import android.text.InputFilter;
import android.text.TextWatcher;
import android.util.Log;
import android.view.Display;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnFocusChangeListener;
import android.view.View.OnKeyListener;
import android.view.ViewGroup;
import android.view.ViewGroup.LayoutParams;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.GridView;
import android.widget.HorizontalScrollView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

public class PlayGame_BK extends Activity {
	/** Called when the activity is first created. */
	public String tag = "PlayGame";
	HorizontalScrollView hScroll;
	EditText edit;
	EditText edtName;
	EditText edtKind;
	GridView gridView;
	Button btnSubmit;
	Button btnHint;
	Button btnFaceBook;
	EditViewAdapter EditAdapter;
	LinearLayout lnAcross;
	LinearLayout lnDown;
	int row, column, idGame;
	int countNum = 0;
	int countID = 0;
	String pathImg = null;
	int idEdit = 0;
	int wText = 35; // width of textbox
	ArrayList<clsWordDetail> arrList;
	ListView lv1;
	LinearLayout lnMainLayout;
	LinearLayout lnGridItem;
	LinearLayout lnGrid;

	ImageView view2;

	ListView lstAcross, lstDown;

	CrosswordHintArrayAdapter acrossAdapter;
	CrosswordHintArrayAdapter downAdapter;

	ArrayList<Integer> acrossHint;
	ArrayList<Integer> downHint;

	CrossWordDbAdapter mDbHelper;
	// Cursor cursor;

	int totalId = 10;
	// clsTime time;
	// Timer
	TextView lblDisplayTime;
	private int hour;
	private int minute;
	private int second;
	private Handler _myHandler;
	private Runnable _myTask;

	// ////////

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		try {
			setContentView(R.layout.play_game);

			hScroll = (HorizontalScrollView) findViewById(R.id.hScroll);

			mDbHelper = new CrossWordDbAdapter(this);
			mDbHelper.open();

			countID = 0;
			arrList = new ArrayList<clsWordDetail>();

			lblDisplayTime = (TextView) findViewById(R.id.lbl_display_time);
			lstAcross = (ListView) findViewById(R.id.lstAcross);
			lstDown = (ListView) findViewById(R.id.lstDown);

			lnMainLayout = (LinearLayout) findViewById(R.id.MainLayout);
			lnAcross = (LinearLayout) findViewById(R.id.lnAcross);
			lnDown = (LinearLayout) findViewById(R.id.lnDown);
			// set width, height
			lnGrid = (LinearLayout) findViewById(R.id.lnGrid);
			// ////

			row = 13;
			column = 13;

			gridView = (GridView) findViewById(R.id.grid);
			// gridView.setNumColumns(column);

			// editAdapter = new EditTextAdapter(this);
			// EditAdapter = new EditViewAdapter(this, (row * column) + 1);
			// EditAdapter.setCount((row * column) + 1);
			// gridView.setAdapter(EditAdapter);

			// loadList();
			loadDetail();

			// Timer
			_myTask = new MyTimerTask();
			_myHandler = new Handler();
			_myHandler.postDelayed(_myTask, 1000);
			// ////////

			// get width of screen
			Display display = getWindowManager().getDefaultDisplay();
			int width = display.getWidth();

			lnDown.setLayoutParams(new LinearLayout.LayoutParams(width, LayoutParams.FILL_PARENT));
			lnAcross.setLayoutParams(new LinearLayout.LayoutParams(width, LayoutParams.FILL_PARENT));
			// lnGrid.setLayoutParams(new LinearLayout.LayoutParams(width, 33 * row));
			lnGrid.setLayoutParams(new LinearLayout.LayoutParams(33 * column, 33 * row + 10));

			// Set background for game
			setBackground();
		} catch (Exception ex) {
			Log.e(tag, "OnCreate() Error:" + ex.getMessage());
		}
	}

	public void setBackground() {
		try {
			if (pathImg != null && !pathImg.equals("")) {
				Bitmap bitmap = BitmapFactory.decodeFile(pathImg);
				BitmapDrawable background = new BitmapDrawable(bitmap);
				lnMainLayout.setBackgroundDrawable(background);
			}
		} catch (Exception ex) {
			Log.e(tag + "setBackground:", "Error:" + ex.getMessage());
		}
	}

	private boolean getGame(int id) {
		Cursor cur = null;
		try {
			cur = mDbHelper.getGame(id);
			if (cur == null)
				return false;
			cur.moveToNext();
			row = cur.getInt(0);
			column = cur.getInt(1);
			pathImg = cur.getString(4);

			EditAdapter = new EditViewAdapter(this, (row * column) + 1);
			gridView.setNumColumns(column);
			gridView.setAdapter(EditAdapter);

			Log.i(tag, "getGame() id:" + id + "; (row, col)=" + row + "," + column);

		} catch (Exception ex) {
			Log.e(tag, "getGame() Error: " + ex);
			return false;
		} finally {
			try {
				cur.close();
			} catch (Exception ex) {
			}
		}
		return true;
	}

	private void loadDetail() {
		Log.i(tag, "loadDetail......");
		Cursor cur = null;
		ArrayList<String> acrossHints = new ArrayList<String>();
		acrossHint = new ArrayList<Integer>();
		ArrayList<String> downHints = new ArrayList<String>();
		downHint = new ArrayList<Integer>();
		clsWordDetail detail;
		int id;
		try {

			for (int i = 0; i < totalId; i++) {
				id = randId(totalId + 1);
				if (getGame(id)) {
					cur = mDbHelper.GetDetail(id);
					startManagingCursor(cur);
					if (cur != null) {
						Log.i(tag, "get data Hint...");
						while (cur.moveToNext()) {
							detail = new clsWordDetail();
							// hint down
							if (cur.getInt(2) == 0) {
								downHints.add(cur.getInt(1) + ") " + cur.getString(5));
								downHint.add(cur.getInt(1));
								detail.setAcross(false);
							}
							// hint across
							else {
								acrossHints.add(cur.getInt(1) + ") " + cur.getString(5));
								acrossHint.add(cur.getInt(1));
								detail.setAcross(true);
							}
							detail.setNum(cur.getInt(1));
							detail.setPos(cur.getInt(3));
							detail.setWords(cur.getString(4));
							arrList.add(detail);
						}
					}
					break;
				}
			}

			Log.i(tag,"size acrossHints: " + acrossHints.size());
			acrossAdapter = new CrosswordHintArrayAdapter(this, acrossHints);
			downAdapter = new CrosswordHintArrayAdapter(this, downHints);

			lstAcross.setAdapter(acrossAdapter);
			lstDown.setAdapter(downAdapter);

		} catch (Exception ex) {
			Log.e(tag, "loadDetail() Error: " + ex);
		} finally {
			try {
				if (cur != null && !cur.isClosed()) {
					cur.close();
				}
				mDbHelper.close();
			} catch (Exception ex) {
			}
		}
	}

	private int randId(int n) {
		Random randomGenerator = new Random();
		return randomGenerator.nextInt(n);

	}

	public class EditViewAdapter extends BaseAdapter {
		Context MyContext;
		private int count;

		public EditViewAdapter(Context _MyContext, int count) {
			MyContext = _MyContext;
			this.count = count;
		}

		public void setCount(int count) {
			this.count = count;
		}

		public int getCount() {
			return count;
		}

		public View getView(int position, View convertView, ViewGroup parent) {
			ExtEditText edt = null;

			try {
				if (convertView == null) {
					countID++;
					// Log.i(tag,"EditViewAdapter() count:" + countID);
					// Create EditText
					edt = new ExtEditText(MyContext);
					edt.setId(countID);
					edt.setWidth(wText);
					// edt.setText(countID + "");

					// Set layout_width and layout height
					edt.setLayoutParams(new GridView.LayoutParams(30, 30));
					// Hide EditTesxt
					edt.setVisibility(View.INVISIBLE);

					// Set length of EditText
					InputFilter[] FilterArray = new InputFilter[1];
					FilterArray[0] = new InputFilter.LengthFilter(1);
					edt.setFilters(FilterArray);

					edt.setOnKeyListener(new OnKeyListener() {

						public boolean onKey(View v, int keyCode, KeyEvent event) {
							// TODO Auto-generated method stub
							ExtEditText edtT = (ExtEditText) v;
							setColorItemList(edtT.getnumEdt(), edtT.isAcross());
							return false;
						}
					});

					edt.setOnClickListener(new OnClickListener() {
						public void onClick(View v) {
							// TODO Auto-generated method stub
							ExtEditText edtT = (ExtEditText) v;
							setColorItemList(edtT.getnumEdt(), edtT.isAcross());
						}
					});

					edt.addTextChangedListener(new TextWatcher() {
						public void onTextChanged(CharSequence s, int start, int before, int count) {
							// TODO Auto-generated method stub

						}

						public void beforeTextChanged(CharSequence s, int start, int count, int after) {
							// TODO Auto-generated method stub

						}

						public void afterTextChanged(Editable str) {
							try {
								if (str.toString().trim().equals(""))
									return;

								ExtEditText edt = (ExtEditText) findViewById(idEdit);
								if (edt == null)
									return;
								// set caps lock
								char[] cc = str.toString().trim().toCharArray();
								if (Character.isLowerCase(cc[0])) {
									edt.setText(str.toString().toUpperCase());
								}
							} catch (Exception ex) {
								Log.e(tag + "afterTextChanged", "Error: " + ex.getMessage());
							}
						}
					});

					edt.setOnFocusChangeListener(new OnFocusChangeListener() {
						public void onFocusChange(View v, boolean hasFocus) {
							if (hasFocus) {
								idEdit = v.getId();
							}
						}
					});

				} else {
					// Log.i(tag,"getView().... ");
					edt = (ExtEditText) convertView;
				}

				if (countID == (row * column) + 1) {
					// Load data to GridView
					loadGird(false);
					// Set width
					int pageWidth = hScroll.getWidth();
					hScroll.smoothScrollTo(pageWidth, 0);
				}
			} catch (Exception ex) {
				Log.e(tag, "onActivityResult() Error: " + ex.getMessage());
			}
			// return MyView;
			return edt;
		}

		public Object getItem(int arg0) {
			// TODO Auto-generated method stub
			return null;
		}

		public long getItemId(int arg0) {
			// TODO Auto-generated method stub
			return 0;
		}
	}

	private boolean checkWord() {
		int id;
		try {
			Log.i(tag, "checkWord()....");
			// clearGrid();
			for (clsWordDetail wd : arrList) {
				char[] chWords = wd.getWords().toCharArray();
				if (wd.isAcross()) {
					for (int i = 0; i < chWords.length; i++) {
						ExtEditText edt = (ExtEditText) findViewById(wd.getPos() + i);
						if (!edt.getText().toString().toUpperCase().equals(chWords[i] + "")) {
							return false;
						}
					}

				} else {
					for (int i = 0; i < chWords.length; i++) {
						id = wd.getPos() + column * i;
						if (id < row * column) {
							ExtEditText edt = (ExtEditText) findViewById(id);
							if (!edt.getText().toString().toUpperCase().equals(chWords[i] + "")) {
								return false;
							}
						}
					}
				}
			}
			return true;
		} catch (Exception ex) {
			Log.e(tag + "checkWord", "Error:" + ex.getMessage());
		}
		return false;
	}

	private void loadGird(boolean text) {
		int id;
		int i = 0, j = 0;
		Log.i(tag, "loadGrid() text:" + text);
		try {
			// clearGrid();
			for (clsWordDetail wd : arrList) {
				char[] chWords = wd.getWords().toCharArray();
				if (wd.isAcross()) {
					for (i = 0; i < chWords.length; i++) {
						ExtEditText edt = (ExtEditText) findViewById(wd.getPos() + i);
						edt.setAcross(wd.isAcross());
						edt.setNumEdt(wd.getNum());
						edt.setVisibility(View.VISIBLE);
						if (text)
							edt.setText(chWords[i] + "");
						if (i == 0) {
							edt.setPos(wd.getPos());
						}
					}

				} else {
					for (j = 0; j < chWords.length; j++) {
						id = wd.getPos() + column * j;
						if (id < row * column) {
							ExtEditText edt = (ExtEditText) findViewById(id);
							edt.setAcross(wd.isAcross());
							edt.setNumEdt(wd.getNum());
							edt.setVisibility(View.VISIBLE);
							if (text)
								edt.setText(chWords[j] + "");
							if (j == 0) {
								edt.setPos(wd.getPos());
							}
						}
					}
				}
			}
		} catch (Exception ex) {
			Log.e(tag, "loadGird() i,j=" + i + "," + j + "; Error: " + ex.getMessage());
		}

	}

	private void setColorItemList(int posCell, boolean isAcross) {
		try {
			if (isAcross == true) {
				for (int i = 0; i < acrossHint.size(); i++) {
					if (acrossHint.get(i) == posCell) {
						acrossAdapter.setSelectedPosition(i);
						downAdapter.setSelectedPosition(-1);
						lstAcross.setSelectionFromTop(i, 0);
					}
				}
			} else {
				for (int i = 0; i < downHint.size(); i++) {
					if (downHint.get(i) == posCell) {
						downAdapter.setSelectedPosition(i);
						acrossAdapter.setSelectedPosition(-1);
						lstDown.setSelectionFromTop(i, 0);
					}
				}
			}
		} catch (Exception ex) {
			Log.e(tag, "setColorItemList() Error:" + ex.getMessage());
		}
	}

	/* Initiating Menu XML file (menu.xml) */
	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		MenuInflater menuInflater = getMenuInflater();
		menuInflater.inflate(R.layout.menu_playgame, menu);
		return true;
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		switch (item.getItemId()) {
		case R.id.mnSubmit:
			if (checkWord()) {
				cancelTimer();
				Toast.makeText(getBaseContext(), "Congratulations!!!!", Toast.LENGTH_SHORT).show();
			} else
				Toast.makeText(getBaseContext(), "Not correct!!!!!", Toast.LENGTH_SHORT).show();

			return true;
		case R.id.mnHint:
			loadGird(true);
			return true;
			// case R.id.mnFaceBook:
			// screencapture();
			// // upload photo to facebook
			// Intent LoginAgain = new Intent(PlayGame.this, UploadPhoto.class);
			// startActivity(LoginAgain);
			// return true;
		default:
			return super.onOptionsItemSelected(item);

		}

	}

	// setup time
	private class MyTimerTask implements Runnable {
		public void run() {
			try {
				second++;
				if (second == 60) {
					second = 0;
					minute++;
					if (minute == 60) {
						minute = 0;
						hour++;
					}
				}

				lblDisplayTime.setText((hour > 9 ? hour : "0" + hour) + ":" + (minute > 9 ? minute : "0" + minute) + ":"
						+ (second > 9 ? second : "0" + second));
				_myHandler.postDelayed(this, 1000);
			} catch (Exception ex) {
				Log.e(tag + "MyTimerTask", "Error: " + ex.getMessage());
			}
		}
	}

	private void cancelTimer() {
		if (_myHandler != null) {
			_myHandler.removeCallbacks(_myTask);
		}
	}

	@Override
	public void onDestroy() {
		super.onDestroy();
		try {
			cancelTimer();
			if (mDbHelper != null)
				mDbHelper.close();
		} catch (Exception ex) {
			Log.e(tag + "onDestroy()", "Error: " + ex.getMessage());
		}
	}

	// public void loadList() {
	// ArrayList<String> acrossHints = new ArrayList<String>();
	// acrossHint = new ArrayList<Integer>();
	// ArrayList<String> downHints = new ArrayList<String>();
	// downHint = new ArrayList<Integer>();
	// clsWordDetail detail;
	// try {
	// arrList.clear();
	// Cursor cur = mDbHelper.GetDetail(idGame);
	// // Cursor cur = mDbHelper.GetDetail(1);
	// startManagingCursor(cur);
	//
	// if (cur != null) {
	// while (cur.moveToNext()) {
	// detail = new clsWordDetail();
	// // hint down
	// if (cur.getInt(2) == 0) {
	// downHints.add(cur.getInt(1) + ".) " + cur.getString(5));
	// downHint.add(cur.getInt(1));
	// detail.setAcross(false);
	// }
	// // hint across
	// else {
	// acrossHints.add(cur.getInt(1) + ".) " + cur.getString(5));
	// acrossHint.add(cur.getInt(1));
	// detail.setAcross(true);
	// }
	// detail.setNum(cur.getInt(1));
	// detail.setPos(cur.getInt(3));
	// detail.setWords(cur.getString(4));
	// arrList.add(detail);
	// }
	// }
	//
	// acrossAdapter = new CrosswordHintArrayAdapter(this, acrossHints);
	// downAdapter = new CrosswordHintArrayAdapter(this, downHints);
	//
	// lstAcross.setAdapter(acrossAdapter);
	// lstDown.setAdapter(downAdapter);
	//
	// if (cur != null && !cur.isClosed()) {
	// cur.close();
	// }
	// mDbHelper.close();
	//
	// } catch (Exception ex) {
	// Log.e(tag + "loadList", ex.getMessage());
	// }
	// }

	// public void screencapture() {
	// View v1 = lnGrid.getRootView();
	//
	// v1.setDrawingCacheEnabled(true);
	// Bitmap bm = v1.getDrawingCache();
	//
	// String extr = Environment.getExternalStorageDirectory().toString();
	// File myPath = new File(extr, "LOST.DIR/test.jpg");
	// FileOutputStream fos = null;
	// try {
	// fos = new FileOutputStream(myPath);
	// bm.compress(Bitmap.CompressFormat.JPEG, 100, fos);
	// fos.flush();
	// fos.close();
	// MediaStore.Images.Media.insertImage(getContentResolver(), bm, "Screen1", "screen2");
	// } catch (FileNotFoundException ex) {
	// // TODO Auto-generated catch block
	// Log.i(tag + "setColorItemList", "File Not Found: " + ex.getMessage());
	// } catch (Exception ex) {
	// // TODO Auto-generated catch block
	// Log.i(tag + "setColorItemList", "Error:" + ex.getMessage());
	// }
	// }
}
